import hashlib
import os
import sys
from django.conf import settings


DEBUG = os.environ.get('DEBUG','on') == 'on'
BASE_DIR = os.path.dirname(__file__)

settings.configure(DUBUG = DEBUG,
	SECRET_KEY = 'thisisthesecrekey',
	ROOT_URLCONF = __name__,
	ALLOWED_HOSTS = ['*'],
	MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware',
		'django.middleware.csrf.CsrfViewMiddleware',
		'django.middleware.clickjacking.XFrameOptionsMiddleware',),
	INSTALLED_APPS=['django.contrib.staticfiles'],
	TEMPLATES=[{
			'BACKEND': 'django.template.backends.django.DjangoTemplates',
			'DIRS':[os.path.join(BASE_DIR, 'templates')],
		},],
	#STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'),),
	STATIC_URL = '/static/',)


from django import forms
from django.conf.urls import url
from django.core.cache import cache
from django.urls import reverse
#from django.core.urlresolvers import reverse
from io import BytesIO
from PIL import Image,ImageDraw
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.template import RequestContext
from django.shortcuts import render
from django.views.decorators.http import etag
import datetime
import hashlib
import os

class ImageForm(forms.Form):
	height = forms.IntegerField(min_value=1,max_value=2000)
	width = forms.IntegerField(min_value=1,max_value=2000)

	def generate2(self,image_format='PNG'):
		height = self.cleaned_data['height']
		width = self.cleaned_data['width']
		key = '{}.{}.{}'.format(width,height,image_format)
		content = cache.get(key)
		if content is None:
			image = Image.new('RGB',(width,height))
			###在图片中间 画上一些文字信息
			draw = ImageDraw.Draw(image)
			text = '{} X {} {}'.format(width,height,datetime.datetime.now())
			textwidth,textheight = draw.textsize(text)
			if textwidth < width and textheight < height:
				texttop = (height - textheight) // 2
				textleft = (width - textwidth) // 2
				draw.text((textleft,texttop),text,fill=(255,255,255))
			### 结束
			content = BytesIO()
			image.save(content,image_format)
			content.seek(0)
			cache.set(key,content,60 * 60)
		return content

def generate_etage(request,width,height):
	content = 'Hello Word {} X {}'.format(width,height)
	return hashlib.sha1(content.encode('utf-8')).hexdigest()

# 加上etag之后，刷新浏览器，服务端直接返回一个 304 使用浏览器缓存
@etag(generate_etage)
def img(request,width,height):
	form = ImageForm({'height':height,'width':width})
	if form.is_valid():
		img = form.generate2()
		return HttpResponse(img,content_type='image/PNG')
	else:
		return HttpResponseBadRequest('111111111111111')
	
def demo(request):
	return HttpResponse('OK')


def demo1(request):
	return render(request,'demo.html',{'title':'Hello Word'})



def index(request):
	return render(request,'home.html',{'title':'Hello Word'})


#不知道为什么 http://127.0.0.1:8000/demo1/ 和 http://127.0.0.1:8000/ 一直报500错误，还找不到问题在哪里
#能确定的就是 return render(request,'demo.html',{'title':'Hello Word'}) 这句的问题
#换成 return HttpResponse('OK') 就没有问题
urlpatterns = [url(r'^imgage/(?P<width>[0-9]+)x(?P<height>[0-9]+)$',img),
			   url(r'^demo/$',demo),
			   url(r'^demo1/$',demo1),
			  url(r'^$',index)]


if __name__ == "__main__":
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)
